package Solutions;

import java.util.List;

/**
 * @Classname ReverseBetween
 * @Description TODO
 * @Date 2021/6/19 17:30
 * @Created by ASUS
 */
public class ReverseBetween {
    static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode reverseBetween(ListNode head, int left, int right) {
        if (head == null || head.next == null) return head;
        // 用一个for循环来找到 left 的位置， 然后从 left的位置开始反转链表
        ListNode pointer = head, prev = head;
        ListNode newHead = new ListNode();
        newHead.next = head;
        for (int i = 0; i < left - 1; i++) {
            prev = pointer;
            pointer = pointer.next;
        }
        // 采用头插法
        prev.next = null;
        ListNode work, tail = pointer;
        for (int i = 0; i < right - left + 1; i++) {
            work = pointer;
            pointer = pointer.next;
            work.next = prev.next;
            prev.next = work;
        }
        tail.next = pointer;
        return newHead;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1,
                new ListNode(2,
                        new ListNode(3, new ListNode(4, new ListNode(5, new ListNode(6))))));
        System.out.println(new ReverseBetween().reverseBetween(head, 1, 5));
    }
}
